<template>
  <div class="ce-example root">
    <div class="ce-example__header">
      <a class="ce-example__header-logo" href="https://codex.so/editor">Editor.js 🤩🧦🤨</a>

      <div class="ce-example__header-menu">
        <a href="https://github.com/editor-js" target="_blank">Plugins</a>
        <a href="https://editorjs.io/usage" target="_blank">Usage</a>
        <a href="https://editorjs.io/configuration" target="_blank">Configuration</a>
        <a href="https://editorjs.io/creating-a-block-tool" target="_blank">API</a>
      </div>
    </div>
    <div class="ce-example__content _ce-example__content--small">
      <div id="editorjs" @mousedown="rightClick"></div>

      <div class="ce-example__button" id="saveButton">
        editor.save()
      </div>

      <div class="ce-example__statusbar">
        Readonly:
        <b id="readonly-state">
          Off
        </b>
        <div class="ce-example__statusbar-button" id="toggleReadOnlyButton">
          toggle
        </div>
      </div>
    </div>
    <div class="ce-example__output">
      <pre class="ce-example__output-content" id="output"></pre>

      <div class="ce-example__output-footer">
        <a href="https://codex.so" style="font-weight: bold;">Made by CodeX</a>
      </div>
    </div>
    <div class="with-cool-menu"></div>
    <div class="context-menu-one btn btn-neutral" @mousedown="rightClick" style="margin:100px 0 0 200px;">right click me</div>
    <div v-show="menuVisible" class="right-menu">
      <div @click="showView">查看</div>
      <div @click="editData">修改</div>
    </div>
  </div>
</template>

<script>
import Header from '@editorjs/header'
import List from '@editorjs/list'
import LinkTool from '@editorjs/link'
import CodeTool from '@editorjs/code'
import Paragraph from '@editorjs/paragraph'
import Embed from '@editorjs/embed'
import Table from '@editorjs/table'
import Checklist from '@editorjs/checklist'
import Marker from '@editorjs/marker'
import Warning from '@editorjs/warning'
import RawTool from '@editorjs/raw'
import Quote from '@editorjs/quote'
import InlineCode from '@editorjs/inline-code'
import Delimiter from '@editorjs/delimiter'
import SimpleImage from '@editorjs/simple-image'
import EditorJS from '@editorjs/editorjs'

export default {
  data() {
    return {
      editor: null,
      menuVisible: false,
      rootTop: 0,
    }
  },
  components: {

  },
  methods: {
    // onInitialized (editor) {
    //   saveData()
    // },
    showView() {
      // setInterval(() => {
      //   console.log('show')
      // }, 1000);
      console.log('show')
      // window.event? window.event.cancelBubble = true : e.stopPropagation() // 停止冒泡

    },
    editData() {
      console.log('edit')
    },
    saveData() {
      this.editor.save().then((savedData) => {
        console.log(savedData)
      })
    },
    rightClick(event) {
      if (event.button !== 2) {
        return
      }
      this.menuVisible = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
      this.menuVisible = true // 显示模态窗口，跳出自定义菜单栏

      event.preventDefault() //关闭浏览器右键默认事件
      window.event? window.event.cancelBubble = true : e.stopPropagation() // 停止冒泡
      window.document.oncontextmenu = function() { //禁用默认右键菜单
        return false
      } 

      var menu = document.querySelector('.right-menu')
      this.styleMenu(event, menu)
    },
    recoverEvent() {
      // 取消鼠标监听事件 菜单栏
      document.removeEventListener('mousedown', this.recoverEvent) // 关掉监听
      window.document.oncontextmenu = function() { //启用默认右键菜单
        return true
      }
      this.menuVisible = false
    },
    styleMenu(event, menu) {
      let target = $(event.target)
      let rootX = $('.root').offset().left
      let rootY = $('.root').offset().top
      let desX = target.offset().left
      let desY = target.offset().top
      let menuOffsetX = 50
      let menuOffsetY = -15

      let menuLeft = desX - rootX + event.offsetX + menuOffsetX
      let menuTop = desY - rootY + event.offsetY + menuOffsetY

      let menuTopOffset = desY - rootY 
      if (menuTop + this.rootTop > document.body.clientHeight) {
        menuTop -= this.rootTop * 0.6
      }

      menu.style.left = menuLeft + 'px'
      menu.style.top = menuTop + 'px'
      document.addEventListener('click', this.recoverEvent, false) // 给整个document新增监听鼠标事件，点击任何位置执行foo方法
    }
  },
  created() {

  },
  mounted() {
    this.rootTop = $('.root').offset().top
    
    this.editor = new EditorJS({
      /**
       * Enable/Disable the read only mode
       */
      readOnly: false,

      /**
       * Wrapper of Editor
       */
      holder: 'editorjs',

      /**
       * Common Inline Toolbar settings
       * - if true (or not specified), the order from 'tool' property will be used
       * - if an array of tool names, this order will be used
       */
      // inlineToolbar: ['link', 'marker', 'bold', 'italic'],
      // inlineToolbar: true,

      /**
       * Tools list
       */
      tools: {
        /**
         * Each Tool is a Plugin. Pass them via 'class' option with necessary settings {@link docs/tools.md}
         */
        header: {
          class: Header,
          inlineToolbar: ['marker', 'link'],
          config: {
            placeholder: 'Header'
          },
          shortcut: 'CMD+SHIFT+H'
        },

        /**
         * Or pass class directly without any configuration
         */
        image: SimpleImage,

        list: {
          class: List,
          inlineToolbar: true,
          shortcut: 'CMD+SHIFT+L'
        },

        checklist: {
          class: Checklist,
          inlineToolbar: true,
        },

        quote: {
          class: Quote,
          inlineToolbar: true,
          config: {
            quotePlaceholder: 'Enter a quote',
            captionPlaceholder: 'Quote\'s author',
          },
          shortcut: 'CMD+SHIFT+O'
        },

        warning: Warning,

        marker: {
          class:  Marker,
          shortcut: 'CMD+SHIFT+M'
        },

        code: {
          class:  CodeTool,
          shortcut: 'CMD+SHIFT+C'
        },

        delimiter: Delimiter,

        inlineCode: {
          class: InlineCode,
          shortcut: 'CMD+SHIFT+C'
        },

        linkTool: LinkTool,

        embed: Embed,

        table: {
          class: Table,
          inlineToolbar: true,
          shortcut: 'CMD+ALT+T'
        },

      },

      /**
       * This Tool will be used as default
       */
      // defaultBlock: 'paragraph',

      /**
       * Initial Editor data
       */
      data: {
        blocks: [
          {
            type: "header",
            data: {
              text: "Editor.js",
              level: 2
            }
          },
          {
            type : 'paragraph',
            data : {
              text : 'Hey. Meet the new Editor. On this page you can see it in action — try to edit this text. Source code of the page contains the example of connection and configuration.'
            }
          },
          {
            type: "header",
            data: {
              text: "Key features",
              level: 3
            }
          },
          {
            type : 'list',
            data : {
              items : [
                'It is a block-styled editor',
                'It returns clean data output in JSON',
                'Designed to be extendable and pluggable with a simple API',
              ],
              style: 'unordered'
            }
          },
          {
            type: "header",
            data: {
              text: "What does it mean «block-styled editor»",
              level: 3
            }
          },
          {
            type : 'paragraph',
            data : {
              text : 'Workspace in classic editors is made of a single contenteditable element, used to create different HTML markups. Editor.js <mark class=\"cdx-marker\">workspace consists of separate Blocks: paragraphs, headings, images, lists, quotes, etc</mark>. Each of them is an independent contenteditable element (or more complex structure) provided by Plugin and united by Editor\'s Core.'
            }
          },
          {
            type : 'paragraph',
            data : {
              text : `There are dozens of <a href="https://github.com/editor-js">ready-to-use Blocks</a> and the <a href="https://editorjs.io/creating-a-block-tool">simple API</a> for creation any Block you need. For example, you can implement Blocks for Tweets, Instagram posts, surveys and polls, CTA-buttons and even games.`
            }
          },
          {
            type: "header",
            data: {
              text: "What does it mean clean data output",
              level: 3
            }
          },
          {
            type : 'paragraph',
            data : {
              text : 'Classic WYSIWYG-editors produce raw HTML-markup with both content data and content appearance. On the contrary, Editor.js outputs JSON object with data of each Block. You can see an example below'
            }
          },
          {
            type : 'paragraph',
            data : {
              text : `Given data can be used as you want: render with HTML for <code class="inline-code">Web clients</code>, render natively for <code class="inline-code">mobile apps</code>, create markup for <code class="inline-code">Facebook Instant Articles</code> or <code class="inline-code">Google AMP</code>, generate an <code class="inline-code">audio version</code> and so on.`
            }
          },
          {
            type : 'paragraph',
            data : {
              text : 'Clean data is useful to sanitize, validate and process on the backend.'
            }
          },
          {
            type : 'delimiter',
            data : {}
          },
          {
            type : 'paragraph',
            data : {
              text : 'We have been working on this project more than three years. Several large media projects help us to test and debug the Editor, to make its core more stable. At the same time we significantly improved the API. Now, it can be used to create any plugin for any task. Hope you enjoy. 😏'
            }
          },
          {
            type: 'image',
            data: {
              url: 'assets/codex2x.png',
              caption: '',
              stretched: false,
              withBorder: true,
              withBackground: false,
            }
          },
        ]
      },
      onReady: function(){
        // saveButton.click();
      },
      onChange: function() {
        console.log('something changed');
      }
    });

    /**
     * Saving button
     */
    const saveButton = document.getElementById('saveButton');

    /**
     * Toggle read-only button
     */
    const toggleReadOnlyButton = document.getElementById('toggleReadOnlyButton');
    const readOnlyIndicator = document.getElementById('readonly-state');


    const cPreview = (function (module) {
      /**
       * Shows JSON in pretty preview
       * @param {object} output - what to show
       * @param {Element} holder - where to show
       */
      module.show = function(output, holder) {
        /** Make JSON pretty */
        output = JSON.stringify( output, null, 4 );
        /** Encode HTML entities */
        output = encodeHTMLEntities( output );
        /** Stylize! */
        output = stylize( output );
        holder.innerHTML = output;
      };

      /**
       * Converts '>', '<', '&' symbols to entities
       */
      function encodeHTMLEntities(string) {
        return string.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      }

      /**
       * Some styling magic
       */
      function stylize(string) {
        /** Stylize JSON keys */
        string = string.replace( /"(\w+)"\s?:/g, '"<span class=sc_key>$1</span>" :');
        /** Stylize tool names */
        string = string.replace( /"(paragraph|quote|list|header|link|code|image|delimiter|raw|checklist|table|embed|warning)"/g, '"<span class=sc_toolname>$1</span>"');
        /** Stylize HTML tags */
        string = string.replace( /(&lt;[\/a-z]+(&gt;)?)/gi, '<span class=sc_tag>$1</span>' );
        /** Stylize strings */
        string = string.replace( /"([^"]+)"/gi, '"<span class=sc_attr>$1</span>"' );
        /** Boolean/Null */
        string = string.replace( /\b(true|false|null)\b/gi, '<span class=sc_bool>$1</span>' );
        return string;
      }

      return module;
    })({})

    /**
     * Saving example
     */
    let _self = this
    saveButton.addEventListener('click', function () {
      _self.editor.save()
        .then((savedData) => {
          cPreview.show(savedData, document.getElementById("output"));
        })
        .catch((error) => {
          console.error('Saving error', error);
        })
    })

    /**
     * Toggle read-only example
     */
    toggleReadOnlyButton.addEventListener('click', async () => {
      const readOnlyState = await _self.editor.readOnly.toggle();

      readOnlyIndicator.textContent = readOnlyState ? 'On' : 'Off';
    });
    
    $('#editorjs').click(function(e) {
      var obj = window.event.srcElement
      var curSel = window.getSelection().toString()
      
      // $('.right-menu').css({
      //   'position': 'absolute',
      //   // 'top': 0,
      //   // 'left': 0,
      //   'top': e.offsetX,
      //   'left': e.offsetY
      // })
    })

    // some build handler to call asynchronously
    function createSomeMenu() {
        return {
            callback: function(key, options) {
                var m = "clicked: " + key;
                window.console && console.log(m) || alert(m);
            },
            items: {
                "edit": {name: "Edit", icon: "edit"},
                "cut": {name: "Cut", icon: "cut"},
                "copy": {name: "Copy", icon: "copy"}
            }
        };
    }

  },
  // mounted() {
    // let taintString = '<div><p style="font-size: 5em;"><b></b>BlockWithText<a onclick="void(0)"></div>'
    // let customConfig = {
    //   b: true,
    //   p: {
    //     style: true,
    //   },
    // }
    // this.api.sanitizer.clean(taintString, customConfig)
 
  // }
}

</script>

<style scoped>
  .ce-example__button {
    cursor: pointer;
    color: red;
  }
  .root {
    position: relative;  
  }
  .right-menu {
    position: absolute;
    background-color: #fff;
    line-height: 30px;
    font-size: 1rem;
    text-align: center;
    color: #444040;
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-radius: 3px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
    white-space: nowrap;
    z-index: 1000;
  }
  .right-menu >div {
    padding: 5px 40px;
    display: block;
    line-height: 34px;
    text-align: center;
    z-index: 1001;
  }
  .right-menu >div:not(:last-child) {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }
  .right-menu >div:hover {
    cursor: pointer;
    background: #66b1ff;
    border-color: #66b1ff;
    color: #fff;
  }
</style>